package main

import (
	"github.com/micro/go-web"
	"global/core"
	"github.com/ngaut/log"
	"net/http"
)

type Server struct {
	Context 	*core.Context
	Manager 	*Manager
	Service 	web.Service
}

func NewServer(
	ctx *core.Context,
	service web.Service) *Server {

	manager := NewManager()
	manager.listening()

	return &Server{
		Context: 	ctx,
		Service:	service,
		Manager: 	manager,
	}
}

// 注册
func (s *Server) register()  {
	// 初始化
	s.handleFunc("/coin/list")
	s.handleFunc("/coin/detail")
	s.handleFunc("/exchange/list")
	s.handleFunc("/pair/list")
	s.handleFunc("/pair/detail")
	s.handleFunc("/coin/like")
}

func (s *Server) Serv() {

	// 注册功能
	s.register()

	if err := s.Service.Run(); err != nil {
		log.Fatalf("Fatal error: server run failed, %s", err)
	}
}

func (s *Server) handleFunc(url string) {
	s.Service.HandleFunc(url, func(writer http.ResponseWriter, request *http.Request) {
		conn, err := upgrader.Upgrade(writer, request, nil)
		if err != nil {
			log.Errorf("Error: connect error: %s", err.Error())
			return
		}

		ip := conn.RemoteAddr().String()
		log.Infof("new client addr: %s", ip)

		obj := s.getObj(url)
		s.Manager.Register(url, s.Context, obj, conn)
	})
}

func (s *Server) getObj(url string) HandlerInterface {
	switch url {
	case "/coin/list":
		return new(CoinRequest)
	case "/coin/detail":
		return new(CoinDetail)
	case "/exchange/list":
		return new(Exchange)
	case "/pair/list":
		return new(ExchangePair)
	case "/pair/detail":
		return new(PairDetail)
	case "/coin/like":
		return new(CoinLike)
	}
	return nil
}

